package com.frogs.ucenter.util.wechat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.SendMessageUtil;
import com.frogs.framework.util.PageList;
import com.frogs.system.web.api.entity.AlertMessageMqEntity;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.UserBaseInfoDao;
import com.frogs.ucenter.dao.UserOpenPlatformInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.UserOpenPlatformInfo;
import com.frogs.ucenter.entity.WechatUserBaseInfo;



/**
 * 接收队列消息，通过微信客服接口发送消息给微信用户
 * @author xiaohei
 *
 */
@Component("wechatMessageMqReceive")
public class WechatMessageMqReceive {
	
	private static final Logger log = LoggerFactory.getLogger(WechatMessageMqReceive.class);
	
	@Resource
	private UserOpenPlatformInfoDao userOpenPlatformInfoDao;
	@Resource
	private UserBaseInfoDao userBaseInfoDao;
	@Resource
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	
	/**
	 * 发送队列消息到微信用户
	 * @param alertMessageMqEntity
	 */
	public void sendToWechatUser(AlertMessageMqEntity alertMessageMqEntity){
		int receiver = alertMessageMqEntity.getReceiver();//接收用户
		
		List<Integer> senders = alertMessageMqEntity.getSenders();  
		
		int sender = alertMessageMqEntity.getSender();//发送用户
		String content = alertMessageMqEntity.getContent();//发送内容
		
		JSONObject json = this.getBaseInfo(receiver, sender);
		log.info("func[sendToWechatUser] userjson = " + json + ", receiver=" + receiver + "; sender=" + sender);
		String openId = (String) json.get("openId");
		String realName = (String) json.get("realName");
		String userNkName = (String) json.get("userNkName");
		
		log.info("func[sendToWechatUser] senders=" + JSONObject.toJSONString(senders));
		String userNKNames = getMyAttentionUserNameByUserIds(senders);
		content = content.replace("openId", openId).replace("realName", realName).replace("userNkNames", userNKNames).replace("userNkName", userNkName);
		log.info("func[sendToWechatUser] content= " + content);
		JSONObject jsonObject = SendMessageUtil.sendTemplatMessage(requestApiHelper.getAccessToken(alertMessageMqEntity.getOpenPlatformId()), content);
		log.info("func[sendToWechatUser] result="+jsonObject);
	}
	
	/**
	 * 获取用户名字符串
	 * @param receivers
	 * @return
	 */
	public String getMyAttentionUserNameByUserIds(List<Integer> senders){
		//String[] ids = (String[])receivers.toArray();
		if(null != senders && senders.size() > 0) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("inUserIdList", senders);
			List<String> names=wechatUserBaseInfoDao.getMyAttentionUserNameByUserIds(map);
			if (names.size() == 1) {
				return names.get(0);
			} else {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < names.size(); i++) {
					sb.append(names.get(i));
					if (i == 4) {
						sb.append("......");
						break;
					}
					if (i != (names.size() - 1)) {
						sb.append("、");
					}
				}
				return sb.toString();
			}
		}
		return "";
	}
	
	/**
	 * 通过发送者和接受者获取openid和realname
	 * @param userId
	 * @return
	 */
	public JSONObject getBaseInfo(int receiver, int sender){
		String openId = this.getOpenidByUserId(receiver);
		String realName = this.getRealNameByUserId(receiver);
		String userNkName = "";
		if(sender > 0) {
			userNkName = this.getRealNameByUserId(sender);
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("openId", openId);
		map.put("realName", realName);
		map.put("userNkName", userNkName);
		
		JSONObject json = new JSONObject(map);
		return json;
	}
	
	/**
	 * 通过用户id获取openid
	 * @param userId
	 * @return
	 */
	public String getOpenidByUserId(int userId){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("eqUserId", userId);
		PageList<UserOpenPlatformInfo> list = userOpenPlatformInfoDao.selectByMap(params, false);
		if(list.size()>0){
			return list.get(0).getOpenId();
		}
		return "";
	}
	
	/**
	 * 根据用户名id获取user_base_info的real_name，需要强制登记这个用户别名
	 * @param userId
	 * @return
	 */
	public String getRealNameByUserId(int userId){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("eqUserId", userId);
		
		List<WechatUserBaseInfo> baseInfos = wechatUserBaseInfoDao.selectByMap(params, false);
		if(null == baseInfos || baseInfos.size() == 0) {
			return "";
		}
		return baseInfos.get(0).getNickName();
	}
	
}
